---
title: "R Notebook"
output: html_notebook
---

This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. 

Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Cmd+Shift+Enter*. 
```{r}
suppressWarnings(library(rpart))
suppressWarnings(library(rpart.plot))
suppressWarnings(library(ISLR))
suppressWarnings(library(knitr))
suppressWarnings(library(caret))
suppressWarnings(library(MASS))
```

```{r}
data <- read.table("data\\test_sample.csv", header=T, sep=",")
```
```{r}
set.seed(1)
fitRTREE <- rpart(Y~X1+X2+X3, data=data, method='poisson', control=rpart.control(cp = 0))
best.CP = fitRTREE$cptable[which.min(fitRTREE$cptable[,"xerror"]),"CP"]
```
```{r}
set.seed(1)
prunedTree <- prune(fitRTREE, cp = best.CP)
printcp(prunedTree)
```
```{r}
set.seed(1)
glmnbfit <- glm.nb(Y~X1+X2+X3, data=data)
```
```{r}
rmse <- function(x) sqrt(mean(x^2))
```
```{r}
treeRmse<-rmse(resid(prunedTree))
```
```{r}
glmnbfitRmse<-rmse(glmnbfit$residuals)
```

```{r}
set.seed(1)
predict(prunedTree, newdata=data.frame(Y=0, X1=4, X2=4, X3=4))
```
```{r}
set.seed(1)
predict(glmnbfit, newdata=data.frame(Y=0, X1=4, X2=4, X3=4))
```
```{r}
pred0Tree<-dpois(0,lambda=predict(prunedTree, newdata=data.frame(Y=0, X1=4, X2=4, X3=4)))
```
```{r}
mu<-predict(glmnbfit,data.frame(Y=0, X1=4, X2=4, X3=4),type="response")
pred0glmnb<-dnbinom(0,mu=mu,size=glmnbfit$theta)
```
```{r}
glmnbfitRmse
treeRmse
pred0glmnb
pred0Tree
```

Add a new chunk by clicking the *Insert Chunk* button on the toolbar or by pressing *Cmd+Option+I*.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the *Preview* button or press *Cmd+Shift+K* to preview the HTML file). 

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike *Knit*, *Preview* does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.

